﻿using System;
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;
using System.Reflection;
using UnityEngine.EventSystems;

public class ScrollViewScript : MonoBehaviour, IEndDragHandler
{
    public Func<List<string>> MoveTopAction;          //Scroll移动到顶部触发
    public Func<List<string>> MoveBottomAction;      //Scroll移动到底部触发
    private ScrollRect _scrollRect;
    private List<GameObject> _showCells;
    private List<string> _showCellsTextName;
    private int _minIndexOfShowCells;
    private int _maxIndexOfShowCells;
    private float _cellHeight;
    private int _maxShowCellsLength = 10;       //最大的cells长度
    private int _addShowCellsLength = 10;       //每次增加的cell长度
    private float _numOfCellsBeforeMove = 1.5f;     //每次刷新移动cell之前,需要移动的cell个数
    private float _scrollRectHeight;            //scroll显示区域长度
    public int _initShowCellsLength = 5;        //初始化时cell长度
    private GameObject _showValueCell;

    void Awake()
    {
        Init();
    }

    void Start()
    {
        MoveTopAction = () => new List<string> {"1", "2", "3"};
    }

    void Update()
    {
        //Debug.Log(_scrollRect.content.localPosition.y + " : " + _scrollRect.normalizedPosition);
        if (Input.GetKeyDown(KeyCode.Q))
        {
            _scrollRect.content.localPosition = new Vector3(0, 90, 0);
        }
    }


    public void OnEndDrag(PointerEventData eventData)
    {
        Debug.Log("123");
    }

    public void Init()
    {
        _showValueCell = (GameObject)Resources.Load("ShowValueCell");
        _scrollRect = transform.GetComponent<ScrollRect>();
        _showCells = new List<GameObject>();
        _showCellsTextName = new List<string>();
        _scrollRect.onValueChanged.AddListener(ButtonsMove);
        _cellHeight = _showValueCell.GetComponent<RectTransform>().sizeDelta.y;
        _scrollRectHeight = GetComponent<RectTransform>().sizeDelta.y;
        FirstInitShowButtons();
        //_scrollRect.content.GetComponent<GridLayoutGroup>().enabled = false;
    }

    void FirstInitShowButtons()
    {
        for (int i = 0; i < _initShowCellsLength; i++)
        {
            GameObject tempButton = (GameObject)Instantiate(_showValueCell);
            _showCells.Add(tempButton);
            tempButton.transform.SetParent(_scrollRect.content);
            tempButton.transform.localScale = Vector3.one;
        }
    }

    /// <summary>
    /// 设置滚动区域初始值
    /// </summary>
    /// <param name="showValueList"></param>
    /// <param name="changeField"></param>
    public void SetScrollContentValue(List<string> showValueList, string changeField)
    {
        _showCellsTextName.AddRange(showValueList);
        _maxShowCellsLength = _maxShowCellsLength < _showCellsTextName.Count
            ? _maxShowCellsLength
            : _showCellsTextName.Count;
        //_scrollRect.content.sizeDelta = new Vector2(_scrollRect.content.sizeDelta.x,
        //    _scrollRect.content.GetComponent<GridLayoutGroup>().cellSize.y * _maxShowCellsLength);
        ChangeScrollContentHeight();
        int tempShowCount = Mathf.Min(_maxShowCellsLength, _initShowCellsLength);
        _minIndexOfShowCells = 0;
        _maxIndexOfShowCells = tempShowCount - 1;
        _scrollRect.normalizedPosition = new Vector2(0, 1);
        for (int showCellIndex = 0; showCellIndex < _initShowCellsLength; showCellIndex++)
        {
            if (showCellIndex < tempShowCount)
            {
                SetCellTextValue(_showCells[showCellIndex], showCellIndex);
                SetCellEvent(_showCells[showCellIndex], changeField);
            }
            else
            {
                _showCells[showCellIndex].SetActive(false);
            }
        }
    }

    void SetCellTextValue(GameObject operateCell, int cellIndex)
    {
        operateCell.SetActive(true);
        Text tempText = operateCell.GetComponentInChildren<Text>();
        tempText.text = _showCellsTextName[cellIndex];
        operateCell.name = cellIndex.ToString();
        operateCell.transform.localPosition = new Vector3(operateCell.transform.localPosition.x,
            -cellIndex * _cellHeight, operateCell.transform.localPosition.z);

    }

    void SetCellEvent(GameObject operateCell, string changeField)
    {
        operateCell.GetComponent<Button>().onClick.RemoveAllListeners();
        operateCell.GetComponent<Button>().onClick.AddListener(delegate()
        {
            ReturnCityValue(operateCell.GetComponentInChildren<Text>().text, changeField);
        });
    }
    void ReturnCityValue(string value, string changeField)
    {
        UIManager.GetInstance().RefrashCurrentCityData(value, changeField);
        _showCellsTextName.Clear();
        _maxShowCellsLength = _addShowCellsLength;
        transform.parent.gameObject.SetActive(false);
    }

    /// <summary>
    /// 修改滚动条的长度
    /// </summary>
    void ChangeScrollContentHeight()
    {
        //_scrollRect.content.sizeDelta = new Vector2(_scrollRect.content.sizeDelta.x,
        //    _scrollRect.content.GetComponent<GridLayoutGroup>().cellSize.y * _maxShowCellsLength);
        _scrollRect.content.sizeDelta = new Vector2(_scrollRect.content.sizeDelta.x,
    _cellHeight * _maxShowCellsLength);
    }

    void ButtonsMove(Vector2 scrollNormalizedPosition)
    {
        //Debug.Log(Time.time + " : " + _scrollRect.content.localPosition);
        if (scrollNormalizedPosition.y >= 0 && scrollNormalizedPosition.y <= 1)
        {
            if ((_scrollRect.content.sizeDelta.y - _scrollRectHeight) * (1 - scrollNormalizedPosition.y) >= (_minIndexOfShowCells + _numOfCellsBeforeMove) * _cellHeight)
            {
                ButtonsMoveDown();
            }
            else if ((_scrollRect.content.sizeDelta.y - _scrollRectHeight) * (1 - scrollNormalizedPosition.y) <= (_maxIndexOfShowCells + 1 - _scrollRectHeight / _cellHeight - _numOfCellsBeforeMove) * _cellHeight)
            {
                ButtonsMoveUp();
            }
        }
        else if (scrollNormalizedPosition.y < 0 && _maxIndexOfShowCells == _maxShowCellsLength - 1)
        {
            MoveBottomAddMoreButton();
        }
        else if (scrollNormalizedPosition.y > 1 && _minIndexOfShowCells == 0)
        {
            MoveTopAddMoreButton();
        }
    }

    void ButtonsMoveDown()
    {
        if (_maxIndexOfShowCells < _maxShowCellsLength - 1)
        {
            _minIndexOfShowCells++;
            _maxIndexOfShowCells++;
            GameObject moveButton = _showCells[0];
            moveButton.GetComponent<RectTransform>().anchoredPosition3D -= new Vector3(0, _initShowCellsLength * _cellHeight, 0);
            _showCells.RemoveAt(0);
            moveButton.GetComponentInChildren<Text>().text = _showCellsTextName[_maxIndexOfShowCells];
            moveButton.name= _maxIndexOfShowCells.ToString();
            _showCells.Add(moveButton);
        }
    }

    void ButtonsMoveUp()
    {
        if (_minIndexOfShowCells > 0)
        {
            _minIndexOfShowCells--;
            _maxIndexOfShowCells--;
            GameObject moveButton = _showCells[_showCells.Count - 1];
            moveButton.GetComponent<RectTransform>().anchoredPosition3D += new Vector3(0, _initShowCellsLength * _cellHeight, 0);
            _showCells.RemoveAt(_showCells.Count - 1);
            moveButton.GetComponentInChildren<Text>().text = _showCellsTextName[_minIndexOfShowCells];
            moveButton.name = _minIndexOfShowCells.ToString();
            _showCells.Insert(0, moveButton);
        }
    }

    void MoveBottomAddMoreButton()
    {
        if (MoveBottomAction != null && _maxShowCellsLength == _showCellsTextName.Count)
        {
            //Ask Controller for more ITEM info
            _showCellsTextName.AddRange(MoveBottomAction());
        }
        if (_maxShowCellsLength != _showCellsTextName.Count)
        {
            _maxShowCellsLength = _maxShowCellsLength + _addShowCellsLength < _showCellsTextName.Count
                ? _maxShowCellsLength + _addShowCellsLength
                : _showCellsTextName.Count;
            //_scrollRect.content.sizeDelta = new Vector2(_scrollRect.content.sizeDelta.x,
            //    _scrollRect.content.GetComponent<GridLayoutGroup>().cellSize.y * _maxShowCellsLength);
            ChangeScrollContentHeight();
            //_scrollRect.normalizedPosition = new Vector2(0,
            //    1 - _scrollRect.content.localPosition.y / (_scrollRect.content.sizeDelta.y - _scrollRectHeight));
        }

    }

    void MoveTopAddMoreButton()
    {
        if (MoveTopAction != null && _minIndexOfShowCells == 0)
        {
            List<string> tempList = MoveTopAction();
            MoveTopAction = null;
            _showCellsTextName.InsertRange(0, tempList);
            //_minIndexOfShowCells += tempList.Count;
            //_maxIndexOfShowCells += tempList.Count;
            for (int i = 0; i <= _maxIndexOfShowCells; i++)
            {
                _showCells[i].GetComponentInChildren<Text>().text = _showCellsTextName[i];
            }
            _maxShowCellsLength += tempList.Count;
            ChangeScrollContentHeight();
            _scrollRect.content.localPosition = new Vector3(0, 90, 0);
            Debug.Log(_scrollRect.content.localPosition);
            //_scrollRect.normalizedPosition = new Vector2(0,
            //1 - _scrollRect.content.localPosition.y / (_scrollRect.content.sizeDelta.y - _scrollRectHeight));
            //修改_scrollRect.normalizedPosition,_scrollRect.content.localPosition.y,_scrollRect.content.sizeDelta.y,_maxShowCellsLength,_minIndexOfShowCells,_maxIndexOfShowCells

        }
    }



}
